<template>
  <div class="message-container" ref="messageContainerRef">
    <MessageArea title="留言板" :subTitle="`(${data.total})`" :isListLoading="isLoading" :list="data.rows" @submit="handleSubmit" />
  </div>
</template>

<script>
import { getMessages, postMessage } from '@/api/message'
import MessageArea from '@/components/MessageArea'
import fetchData from '@/mixins/fetchData'
import mainScroll from '@/mixins/mainScroll'

export default {
  name: 'Message',
  mixins: [fetchData({ total: 0, rows: [] }), mainScroll('messageContainerRef')],
  components: { MessageArea },
  data() {
    return {
      page: 1,
      limit: 10,
    }
  },
  computed: {
    hasMore() {
      return this.data.rows.length < this.data.total
    },
  },
  created() {
    this.$bus.$on('mainScroll', this.handleScroll)
  },
  destroyed() {
    this.$bus.$off('mainScroll', this.handleScroll)
  },
  methods: {
    async fetchData() {
      return await getMessages(this.page, this.limit)
    },
    async fetchMore() {
      if (!this.hasMore) return
      this.isLoading = true
      this.page++
      const resp = await this.fetchData()
      this.data.total = resp.total
      this.data.rows = this.data.rows.concat(resp.rows)
      this.isLoading = false
    },
    handleScroll(dom) {
      if (!dom || this.isLoading) return
      const range = 100
      const dec = Math.abs(dom.scrollTop + dom.clientHeight - dom.scrollHeight)
      if (dec <= range) {
        this.fetchMore()
      }
    },
    async handleSubmit(formData, callback) {
      const resp = await postMessage(formData)
      callback('感谢您的留言')
      this.data.rows.unshift(resp)
    },
  },
}
</script>

<style scoped lang="less">
.message-container {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  padding: 25px 0;
  box-sizing: border-box;
  scroll-behavior: smooth;
  .message-area-container {
    width: 700px;
    margin: 0 auto;
  }
}
</style>
